import { CheckOutlined, QuestionCircleOutlined, UndoOutlined } from '@ant-design/icons';
import { Col, FloatButton, Row, Tooltip } from 'antd';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';
import { useSnapshot } from 'valtio';

import SourceCode from '@/components/SourceCode';
import { finishVulnerable, resetSingleVulnerable, vulnerableProxy } from '@/store/vulnerableStore';
import messageBox from '@/utils/messageBox';

import CauseSolutions from './components/CauseSolutions';
import styles from './index.module.scss';
import { VulnerableProps } from './type';

const VulnerableTemplate: React.FC<VulnerableProps> = props => {
  const { className = '', style, vulnerable, causesSolutions, codeProps } = props;
  const { t } = useTranslation();
  const { pathname } = useLocation();
  const [vul, level] = [pathname.split('/')[1], pathname.split('/')[2]];
  const [tipOpen, setTipOpen] = useState<boolean>(false);
  const vulnerableSnap = useSnapshot(vulnerableProxy);

  const renderPassed = () => {
    return vulnerableSnap.passedVulnerable.includes(pathname) ? (
      <UndoOutlined
        onClick={() => {
          resetSingleVulnerable(pathname);
          messageBox.success({ content: t('vulnerableSingleReset') });
        }}
      />
    ) : (
      <CheckOutlined
        onClick={() => {
          finishVulnerable(pathname);
          messageBox.success({ content: t('vulnerableFinish') });
        }}
      />
    );
  };

  return (
    <Row style={style} className={`${styles.vulnerableTemplate} ${className}`} gutter={0}>
      <Col span={24}>
        <div className="contentBlock">{vulnerable}</div>
      </Col>
      <Col xs={24} sm={24} md={24} lg={12} xl={12}>
        <div className="contentBlock">
          <SourceCode className="h-full" hasPadding={false} {...codeProps} />
        </div>
      </Col>
      <Col xs={24} sm={24} md={24} lg={12} xl={12}>
        <div className="contentBlock">
          <CauseSolutions {...causesSolutions} />
        </div>
      </Col>
      <FloatButton.Group>
        <FloatButton icon={renderPassed()} />
        <Tooltip open={tipOpen} placement="leftBottom" title={<>{t(`${vul}.${level}.tips`)}</>}>
          <FloatButton onClick={() => setTipOpen(!tipOpen)} icon={<QuestionCircleOutlined />} />
        </Tooltip>
      </FloatButton.Group>
    </Row>
  );
};

export default VulnerableTemplate;
